package com.cn.txx.web.listener;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

import com.cn.txx.entity.Module;
import com.cn.txx.utils.Constants;
import com.cn.txx.utils.DBUtil;

public class WebListener implements ServletContextListener{

	Logger logger = Logger.getLogger(this.getClass());
	
	public static ServletContext servletContext = null;
	
	public void contextDestroyed(ServletContextEvent sce) {
		servletContext = null;
		logger.debug("上下文 servletContext...已销毁");
	}
	//初始化 --->因为是lister 这里不能使用spring加载  因为tomcat启动的顺序是ServletContext(context-param)->listener->filter->servlet
	public void contextInitialized(ServletContextEvent sce) {
		servletContext = sce.getServletContext();
		getMoudleCache();
		if(servletContext != null ){
			logger.info("服务器以绑成功定上下文！");
		}else{
			logger.warn("请注意：服务器未绑定上下文！");
		}
		String desc = servletContext.getInitParameter("APP_DESC");
		logger.info(desc);
	}
	
	private void getMoudleCache(){
		Connection conn = DBUtil.getConn(DBUtil.getDBInfo(Constants.DATASOURCE_ZY));
		String sql = " SELECT T_MID,T_DM,T_FDM,T_MNAME,T_MURL,T_MDESC FROM T_MODULE WHERE T_SFJY <> 1";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			int i = 0;
			while(rs.next()){
				 Module module = new Module();
				 module.settDm(DBUtil.trim(rs.getString("T_DM")));
				 module.settFdm(DBUtil.trim(rs.getString("T_FDM")));
				 module.settMdesc(DBUtil.trim(rs.getString("T_MDESC")));
				 module.settMid(DBUtil.trim(rs.getString("T_MID")));
				 module.settMname(DBUtil.trim(rs.getString("T_MNAME")));
				 module.settMurl(DBUtil.trim(rs.getString("T_MURL")));
				 Constants.moduleCache.put(DBUtil.trim(rs.getString("T_MID")), module);
				 i++;
			}
			logger.info("加载权限缓存【"+i+"】条");
		} catch (SQLException e) {
			logger.error("获取权限缓存失败...",e);
		}finally{
			DBUtil.closeDb(conn, rs, ps);
		}	
	}
}
